package com.ruoyi.common.wx;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.http.HttpUtil;
/**
 *	微信登陆工具类
 */
@Component
public class GetOpenIdUtil {

	private String appid = "wxd8a4511905dbbe17";
	//private String secret = "7b48eac5f9acf628e312ef14b8d5f881";


	public String getopenid2(String code) {
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("appid", "wxd8a4511905dbbe17");
		params.put("secret", "7b48eac5f9acf628e312ef14b8d5f881");
		params.put("grant_type", "authorization_code");
		params.put("code", code);
		String result = HttpUtil.get(
				"https://api.weixin.qq.com/sns/oauth2/access_token", params);
		if (result != null) {
			JSONObject jsonObject = JSONObject.parseObject(result);
			return jsonObject.getString("openid");
		}
		return "";
	}


	public String getopenid(String code) {
		System.out.println("微信code："+code);
		BufferedReader in = null;
		//        String url="https://api.weixin.qq.com/sns/jscode2session?appid="
		//                +appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
		String url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid="+appid+"&code="+code+""
				+ "&grant_type=authorization_code&component_appid="+appid+"&component_access_token=COMPONENT_ACCESS_TOKEN" + 
				"";
		try{
			URL weChatUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection connection = weChatUrl.openConnection();
			// 设置通用的请求属性
			connection.setConnectTimeout(5000);
			connection.setReadTimeout(5000);
			// 建立实际的连接
			connection.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = in.readLine()) != null) {
				sb.append(line);
			}
			JSONObject parseObject = JSONObject.parseObject(sb.toString());
			System.out.println("微信返回的参数："+parseObject);
			return parseObject.getString("openid");
		}catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		new GetOpenIdUtil().getopenid2("001yA6Ga1hBKNG0FMcIa1r0j3V3yA6Gj");
	}
}